import os
import json
from plugin_interface import PluginInterface

class JSONPlugin(PluginInterface):
    """基于JSON配置的插件"""
    def __init__(self, config_path):
        self.config_path = config_path
        self.config = {}
        self.app = None
    
    def initialize(self, app):
        """初始化插件"""
        self.app = app
        self._load_config()
    
    def _load_config(self):
        """加载JSON配置"""
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                self.config = json.load(f)
        except Exception as e:
            print(f"加载插件配置失败: {self.config_path}, 错误: {str(e)}")
    
    def on_ui_ready(self):
        """UI就绪后应用配置"""
        self._apply_config()
    
    def _apply_config(self):
        """应用配置到应用"""
        # 应用语法高亮配置
        if 'syntax_highlight' in self.config:
            for tag, color in self.config['syntax_highlight'].items():
                if tag in self.app.highlight_colors:
                    self.app.highlight_colors[tag] = color
                    self.app.editor.tag_configure(tag, foreground=color)
        
        # 应用状态栏配置
        if 'status_bar' in self.config:
            status_config = self.config['status_bar']
            if 'text' in status_config:
                self.app.operation_label.config(text=status_config['text'])
        
        # 应用菜单配置
        if 'menu' in self.config:
            self._apply_menu_config()
        
        # 应用快捷键配置
        if 'shortcuts' in self.config:
            self._apply_shortcut_config()
    
    def _apply_menu_config(self):
        """应用菜单配置"""
        menu_config = self.config['menu']
        
        # 添加新菜单项
        if 'add' in menu_config:
            for item in menu_config['add']:
                if 'menu' in item and 'label' in item and 'command' in item:
                    menu_name = item['menu']
                    label = item['label']
                    command = getattr(self.app, item['command'], None)
                    
                    if command and callable(command):
                        if menu_name == 'File':
                            self.app.file_menu.add_command(label=label, command=command)
                        elif menu_name == 'Run':
                            self.app.run_menu.add_command(label=label, command=command)
                    else:
                        print(f"警告: 找不到命令 {item['command']}")
    
    def _apply_shortcut_config(self):
        """应用快捷键配置"""
        shortcuts = self.config['shortcuts']
        for key, command_name in shortcuts.items():
            command = getattr(self.app, command_name, None)
            if command and callable(command):
                self.app.window.bind(key, lambda event, cmd=command: cmd())
            else:
                print(f"警告: 找不到快捷键命令 {command_name}")
